package activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.hutoubenjg.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import activity.login.ActivityLogin;
import base.BaseActivity;
import base.MyApplcation;
import bean.ConfigBean;
import fragment.IndexFragment;
import fragment.LunTanFragment;
import fragment.MeFragment;
import fragment.DaoLuFragment;
import fragment.StoreFragment;
import logincontroller.LoginController;
import logincontroller.LoginedState;
import logincontroller.UnLoginState;
import presenter.UserPresenter;
import util.NotificationsUtils;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.SPUtils;
import util.utls.UIAlertView;
import util.utls.UpdateManager;
import util.volley.ResultEntity;

import static util.utls.Const.isCloseShop;

/**
 * 主界面
 */
public class MainOneActivity extends BaseActivity implements Observer {
    Button btn_login;
    EditText et_username, et_userpwd;
    View me_layout, index_layout, message_layout, store_layout, luntan_layout2;
    private FragmentManager fragmentManager;
    private IndexFragment indexFragment;
    private StoreFragment storeFragment;
    private DaoLuFragment messageFragment;
    private MeFragment meFragment;
    private LunTanFragment lunTanFragment;
    UserPresenter userPresenter;
    public static MainOneActivity act;
    UIAlertView delDialog;
    private long touchTime = 0;
    private long waitTime = 2000;

    public static MainOneActivity onSetFragment() {
        return act;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main01);
        setStatusBarColor(R.color.main_color_two);
        userPresenter = new UserPresenter(this);
        userPresenter.getConfigApp();
        initView();
        act = this;
        fragmentManager = getSupportFragmentManager();
        // 第一次启动时选中第0个tab
        setTabSelection(0);
    }

    private void initView() {
        message_layout = findViewById(R.id.message_layout);
        store_layout = findViewById(R.id.store_layout);
        index_layout = findViewById(R.id.index_layout);
        me_layout = findViewById(R.id.me_layout);
        luntan_layout2 = findViewById(R.id.luntan_layout2);
        message_layout.setOnClickListener(this);
        index_layout.setOnClickListener(this);
        store_layout.setOnClickListener(this);
        me_layout.setOnClickListener(this);
        luntan_layout2.setOnClickListener(this);

        /**
         * 登录状态
         */
        if ((Boolean) SPUtils.get(MyApplcation.ctx, null,
                Const.IS_LOGINED, false)) {
            LoginController.setLoginState(new LoginedState());
            Log.v("logined", "已经登录");
        } else {
            LoginController.setLoginState(new UnLoginState());
            Log.v("logined", "未登录");
        }

        if (NotificationsUtils.isNotificationEnabled(MainOneActivity.this)) {
            //  ByAlert.alert("通知权限打开了");
        } else {
            //  ByAlert.alert("通知权限没打开");
            delDialog = new UIAlertView(MainOneActivity.this, "温馨提示", "检测到您的手机没有打开通知权限，为了及时收到通知，请手动打开通知权限", "暂不设置", "去设置");
            delDialog.show();
            delDialog.setClicklistener(new UIAlertView.ClickListenerInterface() {
                public void doLeft() {
                    delDialog.dismiss();
                }

                public void doRight() {
                    getAppDetailSettingIntent(MainOneActivity.this);
                    delDialog.dismiss();
                }
            });
        }

    }

    /**
     * 跳转到APP详情设置
     *
     * @param context
     */
    private void getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.index_layout:
                // 当点击了消息tab时，选中第1个tab
                setTabSelection(0);
                break;
            case R.id.store_layout:
                setTabSelection(1);
                break;
            case R.id.message_layout:
                setTabSelection(2);
                break;
            case R.id.luntan_layout2:
                setTabSelection(3);
                break;
            case R.id.me_layout:
                setTabSelection(4);
                break;
        }
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index 每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
     */
    @SuppressLint("ResourceAsColor")
    public void setTabSelection(int index) {
        // 每次选中之前先清楚掉上次的选中状态
        clearSelection();
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                // 当点击了首页tab时，改变控件的图片和文字颜色
                setStatusBarColor(R.color.main_color_two);
                ((ImageView) findViewById(R.id.index_image)).setImageResource(R.drawable.shouye_selected);
                ((TextView) findViewById(R.id.index_text))
                        .setTextColor(getResources().getColor(R.color.blue));
                if (indexFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    indexFragment = new IndexFragment();
                    transaction.add(R.id.content, indexFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(indexFragment);
                }
                break;
            case 1:
                setStatusBarColor(R.color.main_color_two);
                // 当点击了消息tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.store_image)).setImageResource(R.drawable.shangcheng_selected);
                ((TextView) findViewById(R.id.store_text)).setTextColor(getResources().getColor(R.color.blue));
                if (storeFragment == null) {
                    // 如果ContactsFragment为空，则创建一个并添加到界面上
                    storeFragment = new StoreFragment();
                    transaction.add(R.id.content, storeFragment);
                } else {
                    // 如果ContactsFragment不为空，则直接将它显示出来
                    transaction.show(storeFragment);
                }
                break;
            case 2:
                if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
                    Intent intent1 = new Intent(MainOneActivity.this, ActivityLogin.class);
                    startActivity(intent1);
                    return;
                }
                setStatusBarColor(R.color.main_color_two);
                // 当点击了我的tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.message_image)).setImageResource(R.drawable.jiuyuan_selected);
                ((TextView) findViewById(R.id.message_text)).setTextColor(getResources().getColor(R.color.blue));

                if (messageFragment == null) {
                    // 如果SettingFragment为空，则创建一个并添加到界面上
                    messageFragment = new DaoLuFragment();
                    transaction.add(R.id.content, messageFragment);
                } else {
                    // 如果SettingFragment不为空，则直接将它显示出来
                    transaction.show(messageFragment);
                }
                break;
            case 3:
                setStatusBarColor(R.color.main_color_two);
                // 当点击了服务tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.luntan_image)).setImageResource(R.drawable.luntan_selected);
                ((TextView) findViewById(R.id.luntan_text)).setTextColor(getResources().getColor(R.color.blue));
                if (lunTanFragment == null) {
                    // 如果LunTanFragment为空，则创建一个并添加到界面上
                    lunTanFragment = new LunTanFragment();
                    transaction.add(R.id.content, lunTanFragment);
                } else {
                    // 如果NewsFragment不为空，则直接将它显示出来
                    transaction.show(lunTanFragment);
                }

                break;

            case 4:
                setStatusBarColor(R.color.main_color_two);
                // 当点击了服务tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.me_image)).setImageResource(R.drawable.geren_selected);
                ((TextView) findViewById(R.id.me_text)).setTextColor(getResources().getColor(R.color.blue));
                if (meFragment == null) {
                    // 如果NewsFragment为空，则创建一个并添加到界面上
                    meFragment = new MeFragment();
                    transaction.add(R.id.content, meFragment);
                } else {
                    // 如果NewsFragment不为空，则直接将它显示出来
                    transaction.show(meFragment);
                }

                break;

            default:

                break;
        }
        transaction.commit();
    }

    /**
     * 清除掉所有的选中状态。
     */

    private void clearSelection() {
        ((ImageView) findViewById(R.id.message_image)).setImageResource(R.drawable.jiuyuan);
        ((TextView) findViewById(R.id.message_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.index_image)).setImageResource(R.drawable.shouye);
        ((TextView) findViewById(R.id.index_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.store_image)).setImageResource(R.drawable.shangcheng);
        ((TextView) findViewById(R.id.store_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.me_image)).setImageResource(R.drawable.geren);
        ((TextView) findViewById(R.id.me_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.luntan_image)).setImageResource(R.drawable.luntan);
        ((TextView) findViewById(R.id.luntan_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));

    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (indexFragment != null) {
            transaction.hide(indexFragment);
        }
        if (storeFragment != null) {
            transaction.hide(storeFragment);
        }
        if (messageFragment != null) {
            transaction.hide(messageFragment);
        }
        if (meFragment != null) {
            transaction.hide(meFragment);
        }
        if (lunTanFragment != null) {
            transaction.hide(lunTanFragment);
        }

    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.login_success) {
                ByAlert.alert(entity.getData());
//                Intent intent = new Intent(MyApplcation.ctx, RecyclerViewTest.class);
//                startActivity(intent);
            } else if (entity.getEventType() == UserPresenter.login_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.config_success) {
                ConfigBean configBean = (ConfigBean) entity.getData();
                if (configBean.getShopStatus().equals("0")) {
                    isCloseShop = false;
                } else {
                    isCloseShop = true;
                }
                String jgVersion = configBean.getJgVersion();
                int versionInt = Integer.parseInt(jgVersion.replace(".", ""));
                String oldVersion = getAppVersionName(MainOneActivity.this);
                int versionoldInt = Integer.parseInt(oldVersion.replace(".", ""));

                if (versionoldInt < versionInt) {
                    onManager(configBean);
                } else {

                }

                List<ConfigBean.A> bean = new ArrayList<ConfigBean.A>();
                bean.add(configBean.getShopIcons());

                SPUtils.put(this, null,
                        Const.JiaoBiao, bean.get(0).getJiaobiao());

                List<ConfigBean.Phone> beans = new ArrayList<ConfigBean.Phone>();
                beans.add(configBean.getCustomerPhone());
                SPUtils.put(this, null,
                        Const.TEL, beans.get(0).getTel());
            } else if (entity.getEventType() == UserPresenter.config_fail) {

            }
        }
    }

    public void onManager(ConfigBean appUpdateBean) {
        UpdateManager manager = new UpdateManager(this,
                appUpdateBean.getJgUpdateLog() + "",
                appUpdateBean.getJgDownLoadUrl(), appUpdateBean.getJgVersion());
        manager.checkUpdateInfo();
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        int versioncode = 0;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - touchTime) >= waitTime) {
                ByAlert.alert("再按一次退出");
                touchTime = currentTime;
            } else {
                finish();
                //退出后关闭进程
                //   android.os.Process.killProcess(android.os.Process.myPid());
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
